const gulp = require("gulp");
const jsonminify = require("gulp-jsonminify");
const connect = require("gulp-connect");
const del = require("del");
const gulpif = require("gulp-if");
const minimist = require("minimist");

const knownOptions = {
  string: "env",
  default: { env: process.env.NODE_ENV || "production" },
};
const options = minimist(process.argv.slice(2), knownOptions);

gulp.task("clean", function () {
  return del(["./dist"]);
});

gulp.task("json", function () {
  return gulp
    .src("src/**/*.json")
    .pipe(gulpif(options.env === "production", jsonminify()))
    .pipe(gulp.dest("dist"));
});

gulp.task("watch", function (done) {
  gulp.watch("src/**/*.json", gulp.series("json"));
  done();
});

gulp.task("server", function (done) {
  connect.server({
    root: "dist/",
    port: 5000,
    host: "0.0.0.0",
    livereload: true,
    middleware: function (connect, opt) {
      return [
        // 允许跨域的中间件
        function (req, res, next) {
          res.setHeader("Access-Control-Allow-Origin", "*");
          res.setHeader("Access-Control-Allow-Methods", "*");
          next();
        },
      ];
    },
  });
  done();
});

gulp.task("dev", gulp.series("clean", "json", "watch", "server"));
gulp.task("build", gulp.series("clean", "json"));
